﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ShopayServer.Http
{
    struct Router
    {
        public string method;
        public RouteHandle callback;
    };

    public class Route
    {
        // 路由
        private Dictionary<string, Router> routes = new Dictionary<string, Router>();

        public void add(string method, string url, RouteHandle callback)
        {
            Router router;
            // 请求方式大写
            router.method = method.ToUpper();
            router.callback = callback;

            // 加入路由
            routes.Add(url, router);
        }

        public void get(string url, RouteHandle callback)
        {
            add("GET", url, callback);
        }

        public void post(string url, RouteHandle callback)
        {
            add("POST", url, callback);
        }

        public void handle(HttpListenerRequest httpRequest, HttpListenerResponse httpResponse)
        {
            Request request = new Request(httpRequest);
            Response response = new Response(httpResponse);
            
            try
            {
                if (routes.ContainsKey(request.url))
                {
                    Console.WriteLine(request.url);
                    Router router = routes[request.url];

                    // 判断请求类型
                    if (router.method == request.method)
                    {
                        response = router.callback(request, response);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // 发送 Response
                response.send();
            }

            request.Dispose();
            response.Dispose();

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

    public delegate Response RouteHandle(Request request, Response response);
}
